package com.edu.service.impl;

import com.edu.dao.OrderSettingDao;
import com.edu.pojo.OrderSetting;
import com.edu.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;


    public void add(List<OrderSetting> list) {
        if (list != null && list.size()>0){
            for (OrderSetting orderSetting : list) {
                //需要判断当前日期是否已经进行了预约设置
                long countByOrderDate = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
                if (countByOrderDate > 0){
                    orderSettingDao.editNumberByOrderDate(orderSetting);
                }else {
                    orderSettingDao.add(orderSetting);
                }
            }
        }
    }

    public List<Map> getOrderSettingByMonth(String date) {  // date 格式为 yyyy-MM
        String[] split = date.split("-");
        String year = split[0];
        String month = split[1];
        int days = getMonthDays(Integer.parseInt(year), Integer.parseInt(month));
        Map<String , String> map = new HashMap();
        map.put("begin",date+"-1");
        String end = date+"-"+days;
        map.put("end",end);
        List<OrderSetting> list = orderSettingDao.getOrderSettingByMonth(map);

        List<Map> result = new ArrayList();

        if (list != null && list.size() > 0){
            for (OrderSetting orderSetting : list) {
                Map<String,Object> m = new HashMap();
                m.put("date",orderSetting.getOrderDate().getDate());
                m.put("number",orderSetting.getNumber());
                m.put("reservations",orderSetting.getReservations());
                result.add(m);
            }
        }
        return result;
    }

    public void editNumberByDate(OrderSetting orderSetting) throws ParseException {
        Date orderDate = orderSetting.getOrderDate();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = dateFormat.parse(dateFormat.format(orderDate));
        long count = orderSettingDao.findCountByOrderDate(parse);
        orderSetting.setOrderDate(parse);
        if (count > 0){
            orderSettingDao.editNumberByOrderDate(orderSetting);
        }else{
            orderSettingDao.add(orderSetting);
        }
    }

    public static int getMonthDays(int year, int month) {
        if (month == 2){
            if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                return 29;
            }else {
                return 28;
            }
        }else if (month ==4 || month == 6 || month == 9 || month == 11) {
            return 30;
        }else {
            return 31;
        }
    }
}
